<?php

namespace Services\Vip;

use Common\Model\Vip\VipCodeModel;
use Services\BaseService;
use Services\Vip\Exceptions\VipException;

class VipService extends BaseService
{
    /** @var VipCodeModel $vipCodeModel */
    private $vipCodeModel;

    public function __construct()
    {
        $this->vipCodeModel = new VipCodeModel();
    }

    public function codes()
    {

    }


    public function generateVipCode($number = 1, $vipDay = 1)
    {
        $count = 0;
        $alreadyGenerateCodes = [];
        $addCodes = [];

        while ($count < $number) {
            try {
                $code = $this->generateSingleCode($vipDay, $alreadyGenerateCodes);
                $alreadyGenerateCodes[] = $code;
                $addCodes[] = [
                    'code' => $code,
                    'vip_day' => $vipDay,
                    'is_use' => VipCodeModel::NOT_USE,
                    'use_user_id' => 0,
                    'created_at' => get_now_date(),
                    'updated_at' => get_now_date(),
                ];
            } catch (VipException $e) {
            }
            $count++;
        }
        $this->vipCodeModel->addAll($addCodes);
        return true;
    }


    /**
     * 生成VIP码
     * @param $alreadyGenerateCodes
     * @param $time
     * @return void
     */
    private function generateSingleCode($vipDay, $alreadyGenerateCodes = [], $time = 0)
    {
        if ($time > 20) {
            throw new VipException('超出最大尝试次数');
        }
        $code = sprintf("ywld%sA%s%s", $vipDay, generate_random_string(4), generate_random_string(4));
        $record = $this->vipCodeModel->where([
            'code' => $code,
            'is_use' => VipCodeModel::NOT_USE
        ])->find();
        if (in_array($code, $alreadyGenerateCodes) || $record) {
            return $this->generateSingleCode($alreadyGenerateCodes, $time + 1);
        }
        return $code;
    }
}
